<?php
/**
 * Product: proxy_server.
 * Date: 2021-11-12
 * Time: 10:21
 */

namespace ASW\Utility\Buffer;

class Buffer
{
    protected string $_content = '';
    private int    $_position  = 0;
    private string $_lastError = '';

    public function __construct(string $content = '')
    {
        $this->_content = $content;
    }

    public function getHex($from = 0): string
    {
        $bin = $this->getContent($from);
        $hex = strtoupper(bin2hex($bin));
        return implode(' ', str_split($hex, 2));
    }

    public function getContent($from = 0): string
    {
        if ($from > $this->size()) return '';
        if ($from < 0) $from = 0;
        return $from <= 0 ? $this->_content : substr($this->_content, $from);
    }

    public function size(): int
    {
        return strlen($this->_content);
    }

    public function __toString(): string
    {
        return $this->_content;
    }

    public function getLastError(): string
    {
        return $this->_lastError;
    }

    protected function setLastError(string $error)
    {
        $this->_lastError = $error;
    }

    public function move(int $size): bool
    {
        return $this->seek($this->position() + $size);
    }

    public function seek(int $position): bool
    {
        if ($position >= 0 && $position <= $this->size()) {
            $this->_position = $position;
            return true;
        }
        return false;
    }

    public function position(): int
    {
        return $this->_position;
    }

    public function moveToEnd(): bool
    {
        return $this->seek($this->size());
    }

    public function moveToBegin(int $size): bool
    {
        return $this->seek(0);
    }

    public function isBof(): bool
    {
        return $this->position() <= 0;
    }

    public function isEof(): bool
    {
        return $this->position() >= $this->size();
    }
}